import { getShopGoods } from '@/services/shop/api';
import { MsgType, replaceImgHost, showMsg } from '@/utils/utils';
import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons';
import ProForm, { ModalForm } from '@ant-design/pro-form';
import { ActionType, EditableProTable, ProColumns } from '@ant-design/pro-table';
import { Button, Descriptions, Image } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

const OptForm: React.FC<any> = (props) => {
  const {
    handleModalVisible,
    handleAdd,
    actionRef,
    currentRow
  } = props;

  const tableActionRef = useRef<ActionType>();
  const [dataSource, setDataSource] = useState<SHOPAPI.ShopGoods[]>([]);
  const [goodsList, setGoodsList] = useState<SHOPAPI.ShopGoods[]>([]);
  const [imgVisible, setImgVisible] = useState<boolean>(false);

  const columns: ProColumns<SHOPAPI.ShopGoods>[] = [
    {
      title: '图片',
      dataIndex: '',
      width: '13%',
      align: 'center',
      editable: false,
      render: (dom, entity) => {
        if (!entity.attach_list) {
          return null
        }
        return <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Image
            preview={false}
            height={60}
            src={replaceImgHost(entity.attach_list[0].attach_thumb_url || '')}
          />
        </div>
      }
    },
    {
      title: '库存分类',
      dataIndex: 'class_name',
      width: '15%',
      editable: false
    },
    {
      title: '品牌',
      dataIndex: 'brand_name',
      width: '10%',
      editable: false
    },
    {
      title: '名称',
      dataIndex: 'shop_goods_name',
      valueType: 'select',
      width: 300,
      fieldProps: {
        options: goodsList.map(item => ({
          label: item.shop_goods_name,
          value: `${item.shop_goods_id}|${item.goods_py}`
        })),
        showSearch: true,
        filterOption: false,
        onChange: (value: string) => {
          console.info(value);
          const shop_goods_id = value.split('|')[0];
          const goods = goodsList.find(item => item.shop_goods_id === shop_goods_id);
          const key = (tableActionRef.current as any)?.editableKeys[0];
          console.info((tableActionRef.current as any)?.editableKeys[0]);
          const currEditRowIdx = dataSource.findIndex((i: any) => i.id === key);
          if (currEditRowIdx != -1) {
            const currEditRow = dataSource.find((i: any) => i.id === key) as any;
            dataSource[currEditRowIdx] = { ...currEditRow, ...goods } as any;
            setDataSource([...dataSource]);
          }
        }
      },
      formItemProps: {
        rules: [{
          required: true,
          message: '此项是必填项'
        }]
      }
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      width: '20%',
      editable: false
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (dom, record, index, action) => [
        <a key="delete" onClick={() => {
          setDataSource(dataSource.filter(item => item.id !== record.id))
        }}>
          删除
        </a>,

        <a key="editable" onClick={() => {
          (tableActionRef.current as any).editableKeys = [record.id];
          action?.startEditable?.(record.id as string);
        }}>
          修改
        </a>,

        index > 0 ? <a key="up" onClick={() => {
          const list: SHOPAPI.ShopGoods[] = [...dataSource];
          const prevItem = list[index - 1];
          const currentItem = list[index];
          list[index - 1] = currentItem;
          list[index] = prevItem;
          setDataSource(list);
        }}>
          上移
        </a> : null,

        index < dataSource.length - 1 ? <a key="down" onClick={() => {
          const list: SHOPAPI.ShopGoods[] = [...dataSource];
          const nextItem = list[index + 1];
          const currentItem = list[index];
          list[index + 1] = currentItem;
          list[index] = nextItem;
          setDataSource(list);
        }}>
          下移
        </a> : null
      ]
    }
  ];

  const fetchGoodsList = async (params: any) => {
    try {
      const data: SHOPAPI.ShopGoodsList = await getShopGoods(params)
      const list = data.record_list.map(item => {
        return {
          id: item.shop_goods_id + item.sort,
          ...item
        }
      })
      setDataSource(list);
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  useEffect(() => {
    console.info(currentRow);
    if (currentRow.class_id) {
      const params = {
        class_flag: '0',
        current: 1,
        pageSize: 10
      }
      // 一级分类
      if (currentRow.sec_class_list) {
        params['pre_class_id'] = currentRow.class_id
      } else {
        params['shop_class_id'] = currentRow.class_id
      }
      fetchGoodsList(params);
    }
  }, [currentRow]);

  useEffect(() => {
    getShopGoods({
      current: 1,
      pageSize: 10000
    }).then((data: SHOPAPI.ShopGoodsList) => {
      setGoodsList(data.record_list);
    })
  }, []);

  return <ModalForm
    className="modal-form"
    layout="inline"
    width="90%"
    title="编辑分类下商品"
    visible
    modalProps={{
      maskClosable: false
    }}
    onVisibleChange={handleModalVisible}
    onFinish={async (value) => {
      if ((tableActionRef.current as any)?.editableKeys.length > 0) {
        showMsg('您还有未保存的商品信息，请先保存！', MsgType.INFO)
        return
      }
      const params = {
        shop_goods_ids: dataSource.map(item => item.shop_goods_id)
      }
      if (currentRow.sec_class_list) {
        params['pre_class_id'] = currentRow.class_id;
      } else {
        params['class_id'] = currentRow.class_id;
      }
      const success = await handleAdd(params);
      if (success) {
        handleModalVisible(false);
        if (actionRef.current) {
          actionRef.current.reload();
        }
      }
    }}
    submitter={{
      searchConfig: {
        resetText: '取消',
        submitText: '确定'
      }
    }}>
    <ProForm.Group style={{ marginBottom: -10 }}>
      <Descriptions>
        <Descriptions.Item label="店铺商品分类">
          {(currentRow.pName ? currentRow.pName + ' / ' : '') + currentRow.class_name}
        </Descriptions.Item>
      </Descriptions>
    </ProForm.Group>

    <EditableProTable<SHOPAPI.ShopGoods>
      rowKey="id"
      bordered
      value={dataSource}
      actionRef={tableActionRef}
      rowClassName={(record: any) => (record._add ? "newLine" : "")}
      columns={columns}
      editable={{
        type: 'single',
        onCancel: async (key, record, row: any) => {
          tableActionRef.current?.cancelEditable(key);
          (tableActionRef.current as any).editableKeys = [];
          if (row._add === true) {
            setDataSource(dataSource.filter(i => i.id !== key));
          }
        },
        onSave: async (key, row, oRow, newLine) => {
          const idx = dataSource.findIndex(i => i.id === row.id);
          if (idx == -1)
            return;
          setDataSource([...dataSource]);
        },
        actionRender: (row, config, dom) => [dom.save, dom.cancel]
      }}
      recordCreatorProps={false}
    />
    <Button style={{ width: '100%' }} type='dashed' icon={<PlusOutlined />} onClick={() => {
      if ((tableActionRef.current as any)?.editableKeys.length !== 0)
        return;
      const id = window.performance.now().toFixed(0);
      dataSource.push({
        id: id,
        _add: true
      } as any);
      setDataSource([...dataSource]);
      tableActionRef.current?.startEditable(id);
    }}>添加一行数据</Button>
    <div className="modal-tips">
      <ExclamationCircleOutlined />
      <span>编辑分类下商品信息后，请点击下方<strong>确定</strong>按钮保存结果</span>
    </div>
  </ModalForm>
}
export default OptForm;
